#include "winutils.h"
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <sstream>

#ifdef _WIN32

using namespace kraw;

bool WinUtils::logEnabled = true;
HWND WinUtils::hWnd = 0;

void WinUtils::setWindow(HWND _hWnd)
{
	hWnd = _hWnd;
}

HWND WinUtils::getWindow()
{
	return hWnd;
}

void WinUtils::setLogEnabled(bool enabled)
{
	logEnabled = enabled;
}

void WinUtils::win32_printf(const char *format, ...)
{
	if (!logEnabled) return;

	char    buf[4096], *p = buf;
	va_list args;
	int     n;

    va_start(args, format);
    n = _vsnprintf(p, sizeof buf - 3, format, args); // buf-3 is room for CR/LF/NUL
    va_end(args);

    p += (n < 0) ? sizeof buf - 3 : n;

    while ( p > buf  &&  isspace(p[-1]) )
            *--p = '\0';

    *p++ = '\r';
    *p++ = '\n';
    *p   = '\0';

    OutputDebugString(buf);
}

void WinUtils::win32_printfe(const char *format, ...)
{
	if (!logEnabled) return;

	char    buf[4096], *p = buf;
	va_list args;
	int     n;

    va_start(args, format);
    n = _vsnprintf(p, sizeof buf - 3, format, args); // buf-3 is room for CR/LF/NUL
    va_end(args);

    p += (n < 0) ? sizeof buf - 3 : n;

    while ( p > buf  &&  isspace(p[-1]) )
            *--p = '\0';

    *p++ = '\r';
    *p++ = '\n';
    *p   = '\0';

    OutputDebugString(buf);

	std::ostringstream os;
	os << buf;

	MessageBoxA(NULL, os.str().c_str(),  "Message", MB_OK | MB_ICONINFORMATION);
	Sleep(1);
}

#endif
